package edu.zut.hb.software.teach.base.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.io.Serializable;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;

import edu.zut.hb.software.teach.base.BaseAbstractTestCase;
import edu.zut.hb.software.teach.base.domain.BaseEntity;

@ContextConfiguration(locations = { "classpath:/applicationContext-service.xml" })
public abstract class GenericManagerTestCase<PK extends Serializable, T extends BaseEntity<PK>, M extends GenericManager<PK, T>>
		extends BaseAbstractTestCase {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LogManager.getLogger(GenericManagerTestCase.class.getName());

	protected List<T> list;
	protected M manager;

	@SuppressWarnings("unchecked")
	@Test
	public void testCRUD() {
		BaseEntity<PK> expected = null;
		PK expected_Id = (PK) Long.valueOf(10000 + 15L);
		if (logger.isInfoEnabled()) {
			logger.info("testCRUD() - PK expected_Id={}", expected_Id); //$NON-NLS-1$
		}

		int num = 100;
		for (int i = 1; i <= num; i++) {
			T entity = (T) new BaseEntity<PK>();
			entity.setId((PK) Long.valueOf(10000 + i));
			if (expected_Id.equals(entity.getId())) {
				expected = entity;
			}
			this.manager.save(entity);
		}
		BaseEntity<PK> response = this.manager.findById(expected_Id);
		// test save and findById
		assertEquals(expected, response);

		if (logger.isInfoEnabled()) {
			logger.info("testCRUD() - User response={}", response); //$NON-NLS-1$
		}
		List<T> all = this.manager.findAll();
		// test findAlI
		assertEquals(num, all.size());

		/**
		 * test delete
		 */
		this.manager.delete(expected_Id);
		response = this.manager.findById(expected_Id);
		assertNull(response);
		all = this.manager.findAll();
		assertEquals(num - 1, all.size());

	}

}
